import React, { useState } from 'react';
import { formatMessage } from 'umi';
import { Alert, Checkbox } from 'antd';
import { LockOutlined, MailOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import Tabs from '@/zero/components/Tabs';
import Form from '@/zero/components/Ext/Forms/Form';
import Input from '@/zero/components/Input';
import CaptchaFetcher from '@/zero/components/Ext/CaptchaFetcher';
import styles from './index.less';

export default (props) => {
  const {
    account = {},
    mobile,
    onSubmit = (newValue) => {
      console.log('Submit:', newValue);
    },
  } = props;

  const username2rememberMe = localStorage.getItem(`${process.env.PROJECT_CODE}_username@ext`);
  const mobile2rememberMe = localStorage.getItem(`${process.env.PROJECT_CODE}_mobile@ext`);

  const [rememberMe, setRememberMe] = useState(!!username2rememberMe || !!mobile2rememberMe);

  const rememberMeContent = (
    <Checkbox
      checked={rememberMe}
      onChange={(e) => {
        setRememberMe(e.target.checked);
        if (!e.target.checked) {
          localStorage.removeItem(`${process.env.PROJECT_CODE}_username@ext`);
          localStorage.removeItem(`${process.env.PROJECT_CODE}_mobile@ext`);
        }
      }}
    >
      {formatMessage({ id: '记住我' })}
    </Checkbox>
  );

  const renderAccountForm = () => {
    const {
      errorMessage,

      usernameProps,
      passwordProps,

      extraContent,
      ...rest
    } = account;

    const ACCOUNT_LOGIN_TYPE = 'account';

    return (
      <div className={styles.login}>
        <Form
          initialValue={{
            username: username2rememberMe,
          }}
          layout="vertical"
          renderActions={({ disabled: newDisabled, okButton }) => !newDisabled && <>{okButton}</>}
          okText={formatMessage({ id: '登录' })}
          okButtonProps={{
            size: 'large',
            style: { fontWeight: 'bold', width: '100%', marginTop: 24 },
          }}
          markModified={false}
          items={[
            {
              child: (
                <Form.Item noStyle shouldUpdate>
                  {(form) => {
                    const onPressEnter = () => {
                      form.validateFields().then((newRecord) => {
                        onSubmit({ ...newRecord, LOGIN_TYPE: ACCOUNT_LOGIN_TYPE });
                      });
                    };

                    return (
                      <>
                        {errorMessage && (
                          <Alert
                            style={{ marginBottom: 24 }}
                            type="error"
                            showIcon
                            message={errorMessage}
                          />
                        )}

                        <Form.Item
                          name="username"
                          rules={[
                            {
                              required: true,
                              message: formatMessage({ id: '请输入账号' }),
                            },
                          ]}
                          {...usernameProps}
                        >
                          <Input
                            placeholder={formatMessage({ id: '账号@租户标识' })}
                            size="large"
                            prefix={<UserOutlined className={styles.prefixIcon} />}
                            onPressEnter={onPressEnter}
                          />
                        </Form.Item>

                        <Form.Item
                          name="password"
                          rules={[
                            {
                              required: true,
                              message: formatMessage({ id: '请输入密码' }),
                            },
                          ]}
                          {...passwordProps}
                        >
                          <Input.Password
                            placeholder={formatMessage({ id: '密码' })}
                            size="large"
                            prefix={<LockOutlined className={styles.prefixIcon} />}
                            onPressEnter={onPressEnter}
                          />
                        </Form.Item>

                        {rememberMeContent}

                        {typeof extraContent === 'function' ? extraContent({ form }) : extraContent}
                      </>
                    );
                  }}
                </Form.Item>
              ),
            },
          ]}
          onSubmit={(newRecord) => {
            if (rememberMe) {
              localStorage.setItem(
                `${process.env.PROJECT_CODE}_username@ext`,
                newRecord.username || '',
              );
            }
            onSubmit({ ...newRecord, LOGIN_TYPE: ACCOUNT_LOGIN_TYPE });
          }}
          {...rest}
        />
      </div>
    );
  };

  const renderMobileForm = () => {
    const {
      errorMessage,

      mobileProps,
      captchaProps,

      onGetCaptcha,

      extraContent,
      ...rest
    } = mobile;

    const MOBILE_LOGIN_TYPE = 'mobile';

    return (
      <div className={styles.login}>
        <Form
          initialValue={{
            mobile: mobile2rememberMe,
          }}
          layout="vertical"
          renderActions={({ disabled: newDisabled, okButton }) => !newDisabled && <>{okButton}</>}
          okText={formatMessage({ id: '登录' })}
          okButtonProps={{
            size: 'large',
            style: { fontWeight: 'bold', width: '100%', marginTop: 24 },
          }}
          markModified={false}
          items={[
            {
              child: (
                <Form.Item noStyle shouldUpdate>
                  {(form) => (
                    <>
                      {errorMessage && (
                        <Alert
                          style={{ marginBottom: 24 }}
                          type="error"
                          showIcon
                          message={errorMessage}
                        />
                      )}

                      <Form.Item
                        name="mobile"
                        rules={[
                          {
                            required: true,
                            message: formatMessage({
                              id: '请输入手机号',
                            }),
                          },
                          {
                            pattern: /^1\d{10}$/,
                            message: formatMessage({
                              id: '手机号格式错误',
                            }),
                          },
                        ]}
                        {...mobileProps}
                      >
                        <Input
                          placeholder={formatMessage({ id: '手机号' })}
                          size="large"
                          prefix={<MobileOutlined className={styles.prefixIcon} />}
                        />
                      </Form.Item>

                      <Form.Item
                        name="captcha"
                        rules={[
                          {
                            required: true,
                            message: formatMessage({
                              id: '请输入验证码',
                            }),
                          },
                        ]}
                        {...captchaProps}
                      >
                        <Input
                          placeholder={formatMessage({
                            id: '验证码',
                          })}
                          size="large"
                          prefix={<MailOutlined className={styles.prefixIcon} />}
                          addonAfter={
                            <CaptchaFetcher
                              countDown={120}
                              getCaptchaButtonText={formatMessage({ id: '获取验证码' })}
                              getCaptchaSecondText={formatMessage({ id: '秒' })}
                              onGetCaptcha={() => {
                                return new Promise((resolve, reject) => {
                                  form
                                    .validateFields()
                                    .then((finalRecord) => {
                                      if (onGetCaptcha) {
                                        onGetCaptcha(finalRecord, { resolve, reject });
                                      }
                                      resolve();
                                    })
                                    .catch(() => {
                                      reject();
                                    });
                                });
                              }}
                            />
                          }
                        />
                      </Form.Item>

                      {rememberMeContent}

                      {typeof extraContent === 'function' ? extraContent({ form }) : extraContent}
                    </>
                  )}
                </Form.Item>
              ),
            },
          ]}
          onSubmit={(newRecord) => {
            if (rememberMe) {
              localStorage.setItem(
                `${process.env.PROJECT_CODE}_mobile@ext`,
                newRecord.mobile || '',
              );
            }
            onSubmit({ ...newRecord, LOGIN_TYPE: MOBILE_LOGIN_TYPE });
          }}
          {...rest}
        />
      </div>
    );
  };

  if (account && mobile) {
    return (
      <Tabs
        className={styles.tabs}
        tabBarGutter={0}
        tabPanes={[
          {
            id: 1,
            title: formatMessage({ id: '账号密码登录' }),
            content: renderAccountForm(),
          },
          {
            id: 2,
            title: formatMessage({ id: '手机号码登录' }),
            content: renderMobileForm(),
          },
        ]}
      />
    );
  }

  if (mobile) {
    return renderMobileForm();
  }

  if (account) {
    return renderAccountForm();
  }

  return 'DEPRECATED';
};
